package com.ssy.lingxi.order.handler.validator;


import com.ssy.lingxi.order.handler.annotation.DeliverPeriodAnnotation;
import com.ssy.lingxi.order.utils.OrderDateTimeUtil;
import org.springframework.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 时间日期格式字符串校验注解验证类
 * @author 万宁
 * @version 2.0.0
 * @date 2020-07-10
 */
public class DeliverPeriodValidator implements ConstraintValidator<DeliverPeriodAnnotation, String> {
    private boolean nullable = false;

    @Override
    public void initialize(DeliverPeriodAnnotation constraintAnnotation) {
        nullable = constraintAnnotation.nullable();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (!StringUtils.hasText(value)) {
            return nullable;
        }

        switch (value.length()) {
            case 10:
                try {
                    LocalDateTime.parse(value.concat(" 00:00:00"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                } catch (Exception ignored) {
                    return false;
                }
                break;
            case 16:
                try {
                    LocalDateTime.parse(value, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
                } catch (Exception ignored) {
                    return false;
                }
                break;
            case 22:
                return OrderDateTimeUtil.checkDatePeriod(value);
            default:
                return false;
        }

        return true;
    }
}
